package com.boy.rpc.framework.console.utils;

import com.boy.rpc.framework.console.Constant;
import com.boy.rpc.framework.console.bean.RKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by wesley on 2017-03-16.
 */
public class InitKeysCacheUtil {

    private static final Logger logger = LoggerFactory.getLogger(InitKeysCacheUtil.class);

    public static void initRedisKeysCache(RedisTemplate redisTemplate, String name, String keys) {
        logger.debug("----initRedisKeysCache----");
        if(StringUtils.isEmpty(keys)){
            keys = Constant.REDIS_PROPERTIES_KEYS_DEFAULT_VALUE;
        } else {
            Constant.REDIS_PROPERTIES_KEYS_DEFAULT_VALUE = keys;
        }
        for(int i = 0; i<= Constant.REDIS_DEFAULT_DB_SIZE; i++) {
            initRedisKeysCache(redisTemplate, name, i, keys);
        }
    }


    public static void initRedisKeysCache(RedisTemplate redisTemplate, String serverName , int dbIndex, String keys) {
        RedisConnection connection = RedisConnectionUtils.getConnection(redisTemplate.getConnectionFactory());
        connection.select(dbIndex);
        Set<byte[]> keysSet = connection.keys(keys.getBytes());
        connection.close();
        List<RKey> tempList = new ArrayList<RKey>();
        ConvertUtil.convertByteToString(connection, keysSet, tempList);
        Collections.sort(tempList);
        CopyOnWriteArrayList<RKey> redisKeysList = new CopyOnWriteArrayList<RKey>(tempList);
        if(redisKeysList.size()>0) {
            Constant.redisKeysListMap.put(serverName+Constant.DEFAULT_SEPARATOR+dbIndex, redisKeysList);
        }
    }

    public static void logCurrentTime(String code) {
        logger.debug("code:" + code + "当前时间:" + System.currentTimeMillis());
    }
}
